Typescript ReturnType
Typescript includes several useful utility types to enhance the type declarations of your code-base.
The ReturnType
function is one of my favorite ones, as it helps reduce type definition duplication.
Suppose you have the following function definition:
type IsInText = (
text: string
) => (
term: string,
minCount: number,
maxCount?: number,
caseSensitive?: boolean
) => boolean
Now we want to write a function allTermsInText
, that takes the function returned by isInText
as an argument. It should be used like:
allTermsInText(["Typescript", "awesome"], isInText("Typescript is awesome!"))
Here is the definition without the utility type:
type AllTermsInText = (
terms: string[],
search: (
term: string,
minCount: number,
maxCount?: number,
caseSensitive?: boolean
) => boolean
) => boolean
And here the same function definition, but using ReturnType
for the parameters:
let AllTermsInText = (terms: string[], search: ReturnType<IsInText>) => {
return !terms.find(term => !search(term, 1))
}